/*
 * 设置 vuex 存储用户信息及相关操作
 */
import { getData, setData, clearAllData, goLogin } from '/@/utils/auth'
import store from '../index'
import { VuexModule, Module, Mutation, Action, getModule } from 'vuex-module-decorators'

import { IUserState } from '../types'

/**
 * namespaced:boolean 启/停用 分模块
 * stateFactory:boolean 状态工厂
 * dynamic:boolean 在 store 创建之后，再添加到 store 中。开启 dynamic 之后必须提供下面的属性
 * name:string 指定模块名称 
 * store:Vuex.Store 实体 提供初始的 store    
 */
@Module({ dynamic: true, store, name: "user" })
class User extends VuexModule implements IUserState {
    [x: string]: any;
    // user info
    public userInfo = getData('userInfo') || {};
    // token
    public token = getData('token') || '';
    // main info
    store: any;
    public mainInfo = getData('mainInfo') || []

    @Mutation
    SET_TOKEN(token: string) {
        this.token = token
    }
    @Mutation
    SET_USERINFO(userInfo: any) {
        this.userInfo = userInfo
    }
    @Mutation
    SET_MAININFO(mainInfo: any) {
        this.mainInfo = mainInfo
    }

    @Action
    setToken(token: string) {
        this.SET_TOKEN(token);
        setData('token', token)
    }
    @Action
    setUserInfo(userInfo: object) {
        this.SET_USERINFO(JSON.stringify(userInfo));
        setData('userInfo', JSON.stringify(userInfo))
    }
    @Action
    setMainInfo(mainInfo: string[]) {
        this.SET_MAININFO(JSON.stringify(mainInfo));
        setData('mainInfo', JSON.stringify(mainInfo))
    }
    @Action
    clearStore() {
        console.log('clearStore');
        // this.userInfo = {}
        // this.token = ''
        // this.mainInfo = []
        clearAllData()
        goLogin(1)
    }
}

export const userStore = getModule<User>(User);
